package com.olympus.hermes.common.support;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author Mickey
 * @since 2021/1/20
 */
public class PageRequest implements Pageable {
    private Integer current = 0;
    private Integer pageSize = 10;
    private Map<String, String> orders;

    @Override
    public int getPageNumber() {
        return this.getCurrent();
    }

    @Override
    public int getPageSize() {
        return this.pageSize;
    }

    @Override
    public long getOffset() {
        return (long) current * (long) pageSize;
    }

    @Override
    public Sort getSort() {
        return Optional.ofNullable(orders).map(orders -> {
            List<Sort.Order> ordersList = new ArrayList<>();
            orders.forEach((key, value) -> ordersList.add(new Sort.Order(Sort.Direction.valueOf(value), key)));
            return ordersList;
        }).map(Sort::by).orElse(Sort.by("id"));
    }

    @Override
    public Pageable next() {
        return null;
    }

    @Override
    public Pageable previousOrFirst() {
        return null;
    }

    @Override
    public Pageable first() {
        return null;
    }

    @Override
    public boolean hasPrevious() {
        return false;
    }

    public Integer getCurrent() {
        return current + 1;
    }

    public void setCurrent(Integer current) {
        if (!current.equals(0)) {
            current = current - 1;
        }
        this.current = current;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Map<String, String> getOrders() {
        return orders;
    }

    public void setOrders(Map<String, String> orders) {
        this.orders = orders;
    }
}
